package com.jianying.base;

import java.util.List;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.jianying.shared.TableData;
import com.jianying.shared.TableSpec;

public class BaseMapper {

	@Resource
	private SqlSessionTemplate sqlSessionTemplate;
	
	
	public <K> TableData<K> pageTable(String statement, TableSpec spec){
		PageBounds pageBounds = pageBounds(spec);
		List<K> ds = getSqlSessionTemplate().selectList(statement, spec, pageBounds);
		PageList<K> pi = (PageList<K>)ds;
		TableData<K> data = new TableData<K>(pi, pi.getPaginator().getTotalCount());
		return data;
	}
	
	public PageBounds pageBounds(TableSpec spec){
		String orderBy = spec.getOrderBy();
		PageBounds pageBounds = orderBy == null 
				? new PageBounds(spec.getCurrentPage(), spec.getPageSize()) 
				: new PageBounds(spec.getCurrentPage(), spec.getPageSize(), 
						com.github.miemiedev.mybatis.paginator.domain.Order.formString(orderBy));
	    return pageBounds;
	}
	
	public SqlSessionTemplate getSqlSessionTemplate() {
		return sqlSessionTemplate;
	}

	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}
	
}
